package com.rtsapp.server.domain.mysql.hibernate.impl;

import java.io.File;
import java.util.concurrent.atomic.AtomicLong;

import com.rtsapp.server.logger.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtils {

	private static final Logger logger =com.rtsapp.server.logger.LoggerFactory.getLogger(HibernateUtils.class);

	private static Configuration config;
	private static SessionFactory sessionFactory;
	private static AtomicLong sessionOpenTimes = new AtomicLong(0);
	private static AtomicLong sessionCloseTimes = new AtomicLong(0);

	private static String cfgFile;
	private static String url;
	private static String user;
	private static String pwd;

	public static void init(String file) {
		try {
			config = new Configuration(); // .setInterceptor( new
											// HibernateInterceptor( ) );

			File hibernateCfgFile = new File(file);// ServerEntrance.serverPath
													// +
													// "provider/hibernate.cfg.xml"
													// );

			if (!hibernateCfgFile.exists()) {
				logger.error("服务器配置文件不存在:" + hibernateCfgFile.getPath());
				throw new HibernateException("服务器配置文件不存在");
			}

			config.configure(hibernateCfgFile);

			ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
					.applySettings(config.getProperties()).build();
			sessionFactory = config.buildSessionFactory(serviceRegistry);
			cfgFile = file;
			url = config.getProperty("hibernate.connection.url");
			user = config.getProperty("hibernate.connection.username");
			pwd = config.getProperty("hibernate.connection.password");

			logger.info("加载数据库配置文件成功");
		} catch (HibernateException e) {
			logger.error("加载hibernate配置文件失败", e);
			throw e;
		}
		logger.info("Hibernate Cfg File:" + cfgFile);
		logger.info("Server URL:" + url);
		logger.info("Server USER:" + user);
		logger.info("Server PWD:" + pwd);
	}

	public static void destroy() {
		logger.info("destroy(), close sessionFactory");
		try {
			sessionFactory.close();
		} catch (HibernateException e) {
			logger.error("destroy(), close sessionFactory error", e);
		}
	}

	public static Session openSession() {
		logger.info("==========begin openSession()=========== " );
		Session session = sessionFactory.openSession();
		sessionOpenTimes.incrementAndGet();
		logger.info("==========openSession() success, open session times " + sessionOpenTimes.get() );
		
		return session;
	}

	public static void closeSession(Session session) {
		logger.info("closeSession(session), close session");
		try {
			if (session != null && session.isOpen()) {
				session.close();
				sessionCloseTimes.incrementAndGet();
				logger.info("closeSession(session) success, close session times" + sessionCloseTimes.get() );
			} else {
				logger.warn("closeSession(session),close session error, is null or not yet open");
			}
		} catch (HibernateException e) {
			logger.error("closeSession(session),close session error", e);
		}
	}

	public static long getSessionOpenTimes() {
		return sessionOpenTimes.get();
	}

	public static long getSessionCloseTimes() {
		return sessionCloseTimes.get();
	}

}
